package com.springboot.astra.controller;

import com.springboot.astra.bean.Resource;
import com.springboot.astra.bean.Role;
import com.springboot.astra.bean.User;
import com.springboot.astra.result.DataResult;
import com.springboot.astra.service.ResourceService;
import com.springboot.astra.service.RoleService;
import com.springboot.astra.service.UserService;
import com.springboot.astra.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/resource")
public class ResourceController {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    ResourceService resourceService;
    @Autowired
    JwtUtils jwtUtils;

    /**
     * 根据权限获取资源
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping("/getResource")
    public DataResult getResource(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String token = request.getHeader("Authorization");
        Claims claims = jwtUtils.parseJwt(token);
        User user = userService.getOneById(Integer.valueOf(claims.getId()));
        //遍历角色获得权限
        List<Resource> resourceList=new LinkedList<>();
        for (Role role:user.getRoles() ) {
//            resourceList.addAll(roleService.getOneByResource(role.getRoleId()).getResources());
            //一个角色的资源菜单
            List<Resource> resources =roleService.getResource(role.getRoleId());
            for (int i=0;i<resources.size();i++){
                //初始化孩子数组
                List<Resource> children=new LinkedList<>();
                //获取resource对象
                Resource resource= resources.get(i);
                //查找该对象下的孩子
                children = resourceService.getResourceByPid(resource.getResourceId());
                //将孩子赋值给resource对象
                resource.setChildren(children);
            }
            resourceList.addAll(resources);
        }
        return DataResult.success(resourceList);
    }

    @GetMapping("/getAll")
    public DataResult getAll() {
        List<Resource> resources = resourceService.getAllResource();
        return DataResult.success(resources);
    }


}
